<template>
	<z-paging ref="paging" v-model="showCoupon" @query="queryList" height="100vh"
		:paging-style="{minHeight: '100vh', backgroundColor: '#F5F6F7'}">
		<template #top>
			<view v-if="showTab" class="navbar">
				<view v-for="(item, index) in menuBar" :key="index" class="nav-item"
					:class="{current: userIndex === index}" @click="onClickItem(index)">
					<text>{{$t(`coupon.tabs.${index}`)}}</text>
				</view>
			</view>
		</template>

		<!-- 优惠券内容区域 -->
		<view class="content-box">
			<view class="tabs-container" :style="{transform: `translateX(-${userIndex * 100}%)`}">
				<view v-for="(tabItem, tabIndex) in menuBar" :key="tabIndex" class="tab-content">
					<view class="list-scroll-content" :class="{'animate-in': userIndex === tabIndex}">
						<view class="coupon-box" v-for="(item, index) in showCoupon" :key="index">
							<view class="coupon-item" :style="{'--item-index': index}">
								<view class="cuoponLeft couponTop2">
									<view class="price">
										￥<text>{{item.FullReduceAmount}}</text>
									</view>
									<view class="type">
										<view class="useWhere" v-if="item.UsePlatform==1">
											{{$t('coupon.labels.platform')}}
										</view>
										<view class="useWhere" v-if="item.UsePlatform==2">
											{{$t('coupon.labels.merchant')}}
										</view>
									</view>
								</view>
								<view class="cuoponRight">
									<view class="name">{{item.CouponName}}</view>
									<view class="bot_right">
										<view class="all_j">
											{{$t('coupon.labels.condition', {amount: item.MinimumConsumption})}}
										</view>
										<view v-if="userIndex == 0 && item.ReceivingMethod == 2" class="all_j">
											所需积分：{{ item.ExchangePoints }}</view>
										<view class="time">
											{{$t('coupon.labels.validity', {start: item.EffectStartDatetime, end: item.EffectEndDatetime})}}
										</view>
										<view class="operateBox" v-if="item.BusinessName && item.BusinessName.length>0" >
											<view class="merchant" @click="goMerchantList(item)">
												查看可用商家
											</view>
											<view class="merchant" v-if="item.CouponDesc" @click="openDesc(item)">
												使用说明
											</view>
										</view>
									</view>
									<view class="right_sydw">
										<view class="couponBtn"
											@click="getCoupon(item,item.ReceivingMethod,item.ExchangePoints)"
											v-if="userIndex==0 && item.ReceivingMethod==1">
											{{$t('coupon.actions.claim')}}
										</view>
										<view class="couponBtn"
											@click="getCoupon(item,item.ReceivingMethod,item.ExchangePoints)"
											v-if="userIndex==0 && item.ReceivingMethod==2">
											{{$t('coupon.actions.pointsExchange')}}
										</view>
									<!-- 	<view class="couponBtn" @click="useCoupon"
											v-if="userIndex==1 && item.CouponStatus==1">{{$t('coupon.actions.useNow')}}
										</view> -->
										<view class="couponBtn" style="background-color: #C8C8C8;"
											v-if="userIndex==2 && item.CouponStatus==2">
											{{$t('coupon.actions.occupied')}}
										</view>
										<view class="couponBtn" style="background-color: #C8C8C8;"
											v-if="userIndex==2 && item.CouponStatus==3">{{$t('coupon.actions.used')}}
										</view>
										<view class="couponBtn" style="background-color: #C8C8C8;"
											v-if="userIndex==3 && item.CouponStatus==4">{{$t('coupon.actions.voided')}}
										</view>
										<view class="couponBtn" style="background-color: #C8C8C8;"
											v-if="userIndex==3 && item.CouponStatus==5">{{$t('coupon.actions.expired')}}
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="descPopup" type="bottom">
			<view class="descPopup">
				<view class="descTitle">
					<uni-icons class="closeIcon" @click="closeDescPopup" type="closeempty" size="30" color="#333"></uni-icons>
					券详情
				</view>
				<view class="descContent">
					<mp-html class="mb40" v-if="descData"
						:content="descData"></mp-html>
				</view>
			</view>
		</uni-popup>
	</z-paging>
</template>

<script>
	import {
		GetAvailableCoupons,
		GetUserReceiveCoupons,
		GetUserCoupons,
		getUserIntegral,
		getUserId
	} from '@/api/homePage.js';
	import TabBar from "@/components/layout/tabbar/index.vue";
	import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";

	export default {
		components: {
			HzSafeArea,
			TabBar
		},
		data() {
			return {
				menuBar: ['领用', '待使用', '已使用', '已失效'],
				showCoupon: [],
				userIndex: 0,
				showTab: true,
				descData:null
			};
		},
		onLoad(options) {
			// 设置导航栏标题
			uni.setNavigationBarTitle({
				title: this.$t('coupon.title')
			})

			const {
				type,
				from
			} = options;
			this.userIndex = type ? 1 : 0;
			if (from === 'integral') this.showTab = false;
		},
		watch: {
			// 监听语言变化，更新导航栏标题
			'$i18n.locale'() {
				uni.setNavigationBarTitle({
					title: this.$t('coupon.title')
				})
			}
		},
		methods: {
			closeDesc() {
				this.$refs.descPopup.close()
			},
			openDesc(item) {
				this.descData = item.CouponDesc
				this.$refs.descPopup.open()
			},
			goMerchantList(item) {
				console.log("showCoupon =>",this.showCoupon);
				console.log("BusinessName =>",item.BusinessName);
				uni.setStorageSync('couponMerchant', item.BusinessName)
				uni.navigateTo({
					url: '/user_subpages/vip/merchantList'
				})
			},
			// 切换头部menu
			onClickItem(index) {
				this.userIndex = index;
				this.$refs.paging.reload();
				this.showCoupon = [];
			},

			// 去使用券
			useCoupon() {
				uni.redirectTo({
					url: '/mall_subpages/mall/index'
				})
			},

			// 领取券
			async getCoupon(obj, type, point) {
				if (obj.ReceivingMethod == 1) {
					await this.getUserReceiveCoupons(obj.Id, type, point);
				} else if (obj.ReceivingMethod == 2) {
					const res = await getUserIntegral();
					if (res.ErrorCode === "0") {
						if (res.Data >= obj.ExchangePoints) {
							await this.getUserReceiveCoupons(obj.Id, type, point);
						} else {
							let num = obj.ExchangePoints - res.Data;
							uni.showToast({
								title: this.$t('coupon.labels.insufficientPoints', {
									num
								}),
								icon: 'none',
								duration: 2000
							})
						}
					}
				}
			},

			// 获取所有优惠券
			async queryList(pageNo, pageSize) {
				try {
					if (this.userIndex === 0) {
						const userDetail = await this.getUser();
						const {
							Data
						} = await GetAvailableCoupons({
							Index: pageNo,
							Size: pageSize,
							UsersId: userDetail.Id
						});

						let list;
						const resData = Data.map(item => ({
							...item,
							EffectStartDatetime: item.EffectStartDatetime.substring(0, 10),
							EffectEndDatetime: item.EffectEndDatetime.substring(0, 10)
						}));
						if (this.showTab) {
							list = resData;
						} else {
							list = resData.filter(item => item.ReceivingMethod == 2);
						}
						list = list.filter(item => item.Id !== 82);
						console.log("list =>",list);
						this.$refs.paging.complete(list);
					} else {
						const {
							Data
						} = await GetUserCoupons({
							Index: pageNo,
							Size: pageSize,
						});
						let list = Data.map(item => ({
							...item.CouponTemple,
							BusinessName:item.BusinessName,
							CouponStatus: item.CouponStatus,
							EffectStartDatetime: item.CouponTemple.EffectStartDatetime.substring(0, 10),
							EffectEndDatetime: item.CouponTemple.EffectEndDatetime.substring(0, 10)
						}));
						
						// 处理过期状态
						list.forEach(item => {
							let now = new Date();
							let nowTime = new Date(this.timestampToTime(now)).getTime();
							let agTime = new Date(item.EffectEndDatetime + ' 23:59:59').getTime();
							if (nowTime > agTime && item.CouponStatus == 1) {
								item.CouponStatus = 5;
							}
						});

						// 根据当前tab筛选数据
						let filteredList = list.filter(item => {
							if (this.userIndex === 0) {
								return item.ReceivingMethod == 1 || item.ReceivingMethod == 2;
							} else if (this.userIndex === 1) {
								return item.CouponStatus == 1;
							} else if (this.userIndex === 2) {
								return item.CouponStatus == 2 || item.CouponStatus == 3;
							} else if (this.userIndex === 3) {
								return item.CouponStatus == 4 || item.CouponStatus == 5;
							}
							return false;
						});
						console.log("filteredList =>",filteredList);
						this.$refs.paging.complete(filteredList);
					}
				} catch (e) {
					this.$refs.paging.complete(false);
				}
			},

			// 获取用户ID
			async getUser() {
				try {
					const userDetail = uni.getStorageSync("UserDetail");
					if (userDetail) {
						return userDetail;
					} else {
						const {
							Data
						} = await getUserId({});
						uni.setStorageSync("UserDetail", Data);
						return Data;
					}
				} catch (e) {
					return null;
				}
			},

			// 领取优惠券
			async getUserReceiveCoupons(couponId, method, needPoint) {
				try {
					const {
						Data
					} = await GetUserReceiveCoupons({
						CouponTempleId: couponId,
						ReceivingMethod: method,
						ExchangePoint: needPoint
					});

					if (Data.CouponCode) {
						uni.showToast({
							title: this.$t('coupon.labels.claimSuccess')
						});
						setTimeout(() => {
							this.$refs.paging.refresh();
						}, 2000);
					} else {
						setTimeout(() => {
							this.$refs.paging.refresh();
						}, 1000);
					}
				} catch (e) {
					console.error('领取优惠券失败:', e);
				}
			},

			timestampToTime(timestamp) {
				var date = new Date(timestamp);
				var Y = date.getFullYear() + '-';
				var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
				var D = date.getDate() + ' ';
				var h = date.getHours() + ':';
				var m = date.getMinutes() + ':';
				var s = date.getSeconds();
				return Y + M + D + h + m + s;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.descPopup{
		background-color: #fff;
		border-top-left-radius: 10rpx;
		border-top-right-radius: 10rpx;
		.descTitle{
			text-align: center;
			padding: 30rpx 0;
			font-size: 34rpx;
			font-weight: 600;
			position: relative;
			.closeIcon{
				position: absolute;
				left: 20rpx;
				top: 20rpx;
				font-weight: 500;
			}
		}
		.descContent{
			padding: 30rpx;
			width: 100%;
			box-sizing: border-box;
		}
	}
	/* 顶部导航栏样式 */
	.navbar {
		display: flex;
		height: 98rpx;
		background: #FFFFFF;
		position: relative;
		z-index: 10;
		box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 24rpx;
			color: #666;
			position: relative;
			transition: all 0.3s ease;
			cursor: pointer;

			text {
				display: inline-block;
				padding: 10rpx 30rpx;
				border-radius: 30rpx;
				transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
				position: relative;
				z-index: 1;

				&:after {
					content: '';
					position: absolute;
					bottom: 6rpx;
					left: 50%;
					width: 0;
					height: 3rpx;
					background-color: #00BFFF;
					transition: width 0.3s ease, left 0.3s ease;
					z-index: 0;
				}
			}

			&:active text {
				transform: scale(0.95);
			}

			&.current {
				text {
					font-size: 30rpx;
					font-weight: 600;
					background-color: #00BFFF;
					color: #FFFFFF;
					transform: translateY(0) scale(1);
					animation: popIn 0.4s ease;

					@keyframes popIn {
						0% {
							transform: translateY(10rpx) scale(0.9);
							opacity: 0.7;
						}

						70% {
							transform: translateY(-5rpx) scale(1.05);
						}

						100% {
							transform: translateY(0) scale(1);
						}
					}
				}

				&:after {
					content: none;
				}
			}
		}
	}

	/* 内容区域样式 */
	.content-box {
		position: relative;
		width: 100%;
		overflow: hidden;
	}

	/* 横向排列的tab容器 */
	.tabs-container {
		display: flex;
		width: 100%;
		transition: transform 0.4s cubic-bezier(0.23, 1, 0.32, 1);
		will-change: transform;
	}

	.tab-content {
		flex: 0 0 100%;
		width: 100%;
	}

	.list-scroll-content {
		height: 100%;
		padding: 24rpx;
		box-sizing: border-box;
		opacity: 0;
		transform: translateY(30rpx);
		transition: all 0.6s cubic-bezier(0.19, 1, 0.22, 1);

		&.animate-in {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.coupon-box {
		position: relative;
		display: flex;
		margin-bottom: 24rpx;

		.coupon-item {
			background-color: #fff;
			width: 100%;
			border-radius: 16rpx;
			display: flex;
			animation: fadeInUp 0.5s ease forwards;
			animation-delay: calc(0.1s * var(--item-index, 0));
			will-change: transform, opacity;
			transition: all 0.3s ease;
			box-shadow: 0 2rpx 20rpx rgba(0, 0, 0, 0.05);
			position: relative;
			overflow: hidden;

			&::before {
				content: '';
				position: absolute;
				left: 32%;
				top: 0;
				bottom: 0;
				width: 2rpx;
				background: radial-gradient(circle at center, #f0f0f0 0, #f0f0f0 2rpx, transparent 3rpx);
				background-size: 2rpx 12rpx;
				background-repeat: repeat-y;
			}

			@keyframes fadeInUp {
				from {
					opacity: 0;
					transform: translateY(30rpx);
				}

				to {
					opacity: 1;
					transform: translateY(0);
				}
			}

			&:active {
				transform: scale(0.98);
				box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
			}

			.cuoponLeft {
				width: 32%;
				height: 100%;
				color: #fff;
				text-align: center;
				position: relative;
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.price {
					font-size: 28rpx;
					font-weight: 500;
					line-height: 1;
					margin-bottom: 16rpx;

					text {
						font-size: 64rpx;
						font-weight: 600;
						margin-left: 4rpx;
					}
				}

				.type {
					.useWhere {
						font-size: 26rpx;
						background: rgba(255, 255, 255, 0.2);
						padding: 4rpx 16rpx;
						border-radius: 20rpx;
					}
				}
			}

			.cuoponRight {
				width: 68%;
				height: 100%;
				padding: 32rpx;
				position: relative;
				box-sizing: border-box;

				.name {
					font-size: 32rpx;
					color: #333;
					font-weight: 600;
					margin-bottom: 16rpx;
					line-height: 1.4;
					width: 70%;
				}

				.bot_right {
					color: #999;
					font-size: 24rpx;
					line-height: 1.6;

					.all_j {
						margin-bottom: 8rpx;
					}

					.time {
						color: #666;
					}

					.operateBox {
						display: flex;
						flex-wrap: wrap;
					}

					.merchant {
						color: #0099FF;
						padding-left: 20rpx;

						&:first-of-type {
							padding-left: 0;
						}
					}
				}

				.right_sydw {
					position: absolute;
					right: 32rpx;
					top: 32rpx;

					.couponBtn {
						min-width: 140rpx;
						height: 52rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						color: #fff;
						font-size: 24rpx;
						font-weight: 500;
						border-radius: 26rpx;
						transition: all 0.3s ease;
						padding: 0 20rpx;
						background: linear-gradient(135deg, #00BFFF 0%, #0099FF 100%);

						&:active {
							transform: scale(0.95);
							opacity: 0.9;
						}

						&[style*="background-color: #C8C8C8"] {
							background: #C8C8C8 !important;
							opacity: 0.8;
						}
					}
				}
			}

			.couponTop2 {
				background: linear-gradient(135deg, #00BFFF 0%, #0099FF 100%);
			}

			.couponTop4 {
				background: linear-gradient(135deg, #FF6B6B 0%, #FF4949 100%);
			}
		}
	}
</style>